import os
import struct

from pymem import Pymem, pattern, process
from win32api import HIWORD, LOWORD, GetFileVersionInfo

from wechat_aes_key import WechatAesKey


class Wechat:
    def __init__(self):
        self.pm = self.get_wechat_process()

    def wecat_process_exist(self) -> bool:
        """微信进程是否存在"""
        return self.pm is not None

    def get_wechat_process(self) -> Pymem:
        """获取微信进程基址"""
        try:
            return Pymem("WeChat.exe")
        except Exception as e:
            return None

    def wechat_init(self) -> WechatAesKey:
        """当前微信初始化"""
        if self.wecat_process_exist():
            WeChatWindll_base = 0
            WeChatWindll_path = ""
            for m in list(self.pm.list_modules()):
                path = m.filename
                if path.endswith("WeChatWin.dll"):
                    WeChatWindll_base = m.lpBaseOfDll
                    WeChatWindll_path = path
                    break

            if not WeChatWindll_path:
                raise ValueError("获取版本失败，请确认本系统是否成功安装了微信！")

            version = GetFileVersionInfo(WeChatWindll_path, "\\")

            msv = version["FileVersionMS"]
            lsv = version["FileVersionLS"]
            version = f"{str(HIWORD(msv))}.{str(LOWORD(msv))}.{str(HIWORD(lsv))}.{str(LOWORD(lsv))}"

            self.version = version
            self.base = WeChatWindll_base
            return WechatAesKey(self.pm, self.version, self.base)
        else:
            raise ValueError("微信进程不存在，请确认微信是否已经启动！")

    def get_wechat_version(self):
        """当前微信版本号"""
        if not self.version:
            raise ValueError("微信版本号获取失败，请先调用 wechat_init 方法初始化！")
        return self.version

    def get_wechat_base(self):
        """当前微信基址"""
        if not self.base:
            raise ValueError("微信基址获取失败，请先调用 wechat_init 方法初始化！")
        return self.base
